#!/bin/bash

#============================nginx nginx nginx===========================================#
function nginx_reload() {
  target_host=$1
  remote_file=$2
  changed=0
  ssh -o StrictHostKeyChecking=no root@${target_host} "
    if [ -f ${remote_file} ];then
      md5_tmp=\`md5sum ${remote_file}.tmp | cut -d' ' -f1\`
      md5_conf=\`md5sum ${remote_file} | cut -d' ' -f1\`
      if [ \${md5_tmp} == \${md5_conf} ];then
        rm -f ${remote_file}.tmp
      else
        mv ${remote_file} ${remote_file}.bak
        mv ${remote_file}.tmp ${remote_file}
        changed=1
      fi
    else
      mv ${remote_file}.tmp ${remote_file}
      changed=1
    fi
    [ \${changed} == 0 ] && exit 0
    nginx -t
    if [ \$? -eq 0 ];then
      [ -f ${remote_file}.bak ] && rm -f ${remote_file}.bak
      nginx -s reload
    else
      echo 'ERROR: nginx -t was failed, please check it!'
      cat -n ${remote_file}
      rm -f ${remote_file}
      [ -f ${remote_file}.bak ] && mv ${remote_file}.bak ${remote_file}
      exit 1
    fi
  "
  exit $?
}


function openresty_reload() {
  target_host=$1
  remote_file=$2
  changed=0
  ssh -o StrictHostKeyChecking=no root@${target_host} "
    if [ -f ${remote_file} ];then
      md5_tmp=\`md5sum ${remote_file}.tmp | cut -d' ' -f1\`
      md5_conf=\`md5sum ${remote_file} | cut -d' ' -f1\`
      if [ \${md5_tmp} == \${md5_conf} ];then
        rm -f ${remote_file}.tmp
      else
        mv ${remote_file} ${remote_file}.bak
        mv ${remote_file}.tmp ${remote_file}
        changed=1
      fi
    else
      mv ${remote_file}.tmp ${remote_file}
      changed=1
    fi
    [ \${changed} == 0 ] && exit 0
    /usr/local/openresty/nginx/sbin/nginx -t
    if [ \$? -eq 0 ];then
      [ -f ${remote_file}.bak ] && rm -f ${remote_file}.bak
      /usr/local/openresty/nginx/sbin/nginx -s reload
    else
      echo 'ERROR: nginx -t was failed, please check it!'
      cat -n ${remote_file}
      rm -f ${remote_file}
      [ -f ${remote_file}.bak ] && mv ${remote_file}.bak ${remote_file}
      exit 1
    fi
  "
  exit $?
}


function send_openresty() {
  ips="10.32.68.3 10.32.33.155"
  local_file=${BASE_DIR}/template/restry.conf
  local_file_tmp=${TMP_DIR}/${env}-${project}-resty.conf
  remote_file=/etc/nginx/${env}.d/${project}.conf
  [ ! -f ${local_file} ] && exit 1
  cp -f ${local_file} ${local_file_tmp}
  domainname=${domainname/\{\{env\}\}/${env}}
  domain_exp=${domainname_exp/\[\\\\w-\]+/${env}}
  my_domainname_exp=${domain_exp%%.*}-vk-l5d-(\[\\\\w-\]+)\\\\.${domain_exp#*.}
  sed -i "s/{{hosts}}/${host}/g" ${local_file_tmp}
  sed -i "s/{{domainname}}/${my_domainname_exp}/g" ${local_file_tmp}
  sed -i "s/{{domainname_ext}}/${domainname}/g" ${local_file_tmp}
  for ip in ${ips}
  do
    scp -o StrictHostKeyChecking=no ${local_file_tmp} root@${target_host}:${remote_file}.tmp
    [ $? -ne 0 ] && rm -f ${local_file_tmp} && exit 1
    openresty_reload ${ip} ${remote_file} || exit 1
  done
  rm -f ${local_file_tmp}
}


function send_jumper() {
  ips="10.32.1.201 10.32.33.7"
  local_file=${BASE_DIR}/template/jumper_ten.conf
  local_file_tmp=${TMP_DIR}/${env}-${project}-jumper.conf
  [ ! -f ${local_file} ] && exit 1
  cp -f ${local_file} ${local_file_tmp}
  if [ -z ${flow_back} ];then
    my_domainname=${domainname/\{\{env\}\}/${env}}
    sed -i "s/{{hosts}}/${host}/g" ${local_file_tmp}
    remote_file=/etc/nginx/conf/${env}.d/${project}.conf
  else
    my_domainname=${domainname/\{\{env\}\}/${drone}}
    sed -i "s/{{hosts}}/${drone_host}/g" ${local_file_tmp}
    remote_file=/etc/nginx/conf/${drone}.d/${project}.conf
  fi
  sed -i "s/{{domainname}}/${my_domainname}/g" ${local_file_tmp}
  for ip in ${ips}
  do
    scp -o StrictHostKeyChecking=no ${local_file_tmp} root@${target_host}:${remote_file}.tmp
    [ $? -ne 0 ] && rm -f ${local_file_tmp} && exit 1
    nginx_reload ${ip} ${remote_file} || exit 1
  done
}


function send_env_host() {
  ip=$1
  local_file=${BASE_DIR}/template/nginx.conf
  local_file_tmp=${TMP_DIR}/${env}-${project}-nginx.conf
  remote_file=/etc/nginx/conf/${project}.conf
  if [ -f ${BASE_DIR}/template/${project}/${env}-nginx.conf ];then
    local_file=${BASE_DIR}/template/${project}/${env}-nginx.conf
  elif [ -f ${BASE_DIR}/template/${project}/router-nginx.conf -a ${router} -eq 1 ]; then
    local_file=${BASE_DIR}/template/${project}/router-nginx.conf
  elif [ -f ${BASE_DIR}/template/${project}/nginx.conf ]; then
    local_file=${BASE_DIR}/template/${project}/nginx.conf
  fi
  cp -f ${local_file} ${local_file_tmp}
  if [ ${router} -eq 1 ];then
    domainname_env=${domainname/\{\{env\}\}/${env}}
    my_domainname="${domainname_env} ${domainname_env/vipkid-qa/vipkid}"
    domainname_exp_env=${domainname_exp/\{\{env\}\}/${env}}
    my_domainname_exp=${domainname_exp_env%%.*}-vk-l5d-(\[\\\\w-\]+)\\\\.${domainname_exp_env#*.}
    sed -i "s/{{projectname}}/${project}/g" ${local_file_tmp}
    sed -i "s/{{linkerd_host}}/${host}/g" ${local_file_tmp}
    sed -i "s/{{listenport}}/4140/g" ${local_file_tmp}
    sed -i "s/{{vfe_listenport}}/${listen_port}/g" ${local_file_tmp}
    sed -i "s/{{domainname_exp}}/${my_domainname} ${my_domainname_exp}/g" ${local_file_tmp}
    sed -i "s/{{env}}/${env}/g" ${local_file_tmp}
    sed -i "s/{{hosts}}/${host}/g" ${local_file_tmp}
  else
    if [ -z ${flow_back} ];then
      domainname_env=${domainname/\{\{env\}\}/${env}}
      my_domainname="${domainname_env} ${domainname_env/vipkid-qa/vipkid}"
      sed -i "s/{{projectname}}/${project}/g" ${local_file_tmp}
      sed -i "s/{{linkerd_host}}/${host}/g" ${local_file_tmp}
      sed -i "s/{{listenport}}/${listen_port}/g" ${local_file_tmp}
      sed -i "s/{{domainname_exp}}/${my_domainname}/g" ${local_file_tmp}
      sed -i "s/{{env}}/${env}/g" ${local_file_tmp}
      sed -i "s/{{hosts}}/${host}/g" ${local_file_tmp}
    else
      domainname_env=${domainname/\{\{env\}\}/${drone}}
      my_domainname="${domainname_env} ${domainname_env/vipkid-qa/vipkid}"
      sed -i "s/{{projectname}}/${project}/g" ${local_file_tmp}
      sed -i "s/{{linkerd_host}}/127.0.0.1/g" ${local_file_tmp}
      sed -i "s/{{listenport}}/${listen_port}/g" ${local_file_tmp}
      sed -i "s/{{domainname_exp}}/${my_domainname}/g" ${local_file_tmp}
      sed -i "s/{{env}}/${env}/g" ${local_file_tmp}
      sed -i "s/{{hosts}}/127.0.0.1/g" ${local_file_tmp}
    fi
  fi
  scp -o StrictHostKeyChecking=no ${local_file_tmp} root@${ip}:${remote_file}.tmp
  [ $? -ne 0 ] && rm -f ${local_file_tmp} && exit 1
  nginx_reload ${ip} ${remote_file} || exit 1
}


function send_drone_host() {
  ip=$1
  local_file=${BASE_DIR}/template/nginx.conf
  local_file_tmp=${TMP_DIR}/${env}-${project}-nginx.conf
  remote_file=/etc/nginx/conf/${project}.conf
  if [ -f ${BASE_DIR}/template/${project}/${env}-nginx.conf ];then
    local_file=${BASE_DIR}/template/${project}/${env}-nginx.conf
  elif [ -f ${BASE_DIR}/template/${project}/${drone}-nginx.conf ];then
    local_file=${BASE_DIR}/template/${project}/${drone}-nginx.conf
  elif [ -f ${BASE_DIR}/template/${project}/router-nginx.conf ]; then
    local_file=${BASE_DIR}/template/${project}/router-nginx.conf
  elif [ -f ${BASE_DIR}/template/${project}/nginx.conf ]; then
    local_file=${BASE_DIR}/template/${project}/nginx.conf
  fi
  cp -f ${local_file} ${local_file_tmp}
  domainname_env=${domainname/\{\{env\}\}/${env}}
  my_domainname="${domainname_env} ${domainname_env/vipkid-qa/vipkid}"
  domainname_exp_env=${domainname_exp/\{\{env\}\}/${env}}
  my_domainname_exp=${domainname_exp_env%%.*}-vk-l5d-(\[\\\\w-\]+)\\\\.${domainname_exp_env#*.}
  sed -i "s/{{projectname}}/${project}/g" ${local_file_tmp}
  sed -i "s/{{linkerd_host}}/${host}/g" ${local_file_tmp}
  sed -i "s/{{listenport}}/4140/g" ${local_file_tmp}
  sed -i "s/{{vfe_listenport}}/${listen_port}/g" ${local_file_tmp}
  sed -i "s/{{domainname_exp}}/${my_domainname} ${my_domainname_exp}/g" ${local_file_tmp}
  sed -i "s/{{env}}/${env}/g" ${local_file_tmp}
  sed -i "s/{{hosts}}/${host}/g" ${local_file_tmp}
  scp -o StrictHostKeyChecking=no ${local_file_tmp} root@${ip}:${remote_file}.tmp
  [ $? -ne 0 ] && rm -f ${local_file_tmp} && exit 1
  nginx_reload ${ip} ${remote_file} || exit 1
}


function set_nginx() {
  if [ ${sync_nginx} -eq 1 ];then
    if [ ${domainname:-NULL} == 'NULL' -o ${domainname} == null ];then
      echo "不存在域名， jumper 和 openresty 不设置nginx！"
    else
      if [ ${router} -eq 0 ];then
        [ ! -f ${BASE_DIR}/template/restry.conf ] && echo "openresty nginx template is not found!" && exit 1
        send_openresty || exit 1
      fi
      [ ! -f ${BASE_DIR}/template/jumper_ten.conf ] && echo "ten jumper nginx template is not found!" && exit 1
      send_jumper || exit 1
    fi

    send_env_host ${host} || exit 1
    if [ ${drone} != 'default' ];then
      send_drone_host ${host} || exit 1
    fi
    [ $? -ne 0 ] && exit 1
  fi
}


# ============================ register vkmq or consul ================================== #
function register_vkmq() {
  if [ ${deploy_type} == 'static' -o ${deploy_type} == 'node' ];then
    # 前段项目使用旧的方法部署
    echo "this is a vfe project, please old method deploy!"
    exit 1
  else
    remote_dir=${REMOTE_DIR}/${project}
    vkmq_app_name=`curl -k -H 'Content-Type:application/json;charset=utf-8' http://lord.nwjx.com.cn/rest/api/vkmq/getAppRealName?projectName=${project}`
    echo ${vkmq_app_name}
    if [ ${drone} != "default" ];then
      curl http://vkmq-admin.nwjx.com.cn/vkmq/testing/addOneEvn\?app=$vkmq_app_name\&env=${env} &
      curl http://vkmq-admin-ten2.nwjx.com.cn/vkmq/testing/addOneEvn\?app=$vkmq_app_name\&env=${env} &
    else
      curl http://vkmq-admin.nwjx.com.cn/vkmq/testing/addOneEvn\?app=$vkmq_app_name\&env=${env}_${drone} &
      curl http://vkmq-admin-ten2.nwjx.com.cn/vkmq/testing/addOneEvn\?app=$vkmq_app_name\&env=${env}_${drone} &
    fi
  fi
}


function unregister_consul() {
  if [ ${router} -eq 1 ];then
    if [[ '${listenport}' ]] && [[ ${listenport} -gt 0 ]]; then
      if [ ${drone} == 'default' ];then
        curl -X PUT http://consul-rg1.nwjx.com.cn/${env}/v1/agent/service/deregister/${project}
        curl -X PUT http://consul-rg2.nwjx.com.cn/${env}/v1/agent/service/deregister/${project}
      else
        curl -X PUT http://consul-rg1.nwjx.com.cn/${env}/v1/agent/service/deregister/${project}-${drone}
        curl -X PUT http://consul-rg2.nwjx.com.cn/${env}/v1/agent/service/deregister/${project}-${drone}
      fi
    fi
  fi
}


function register_consul() {
  if [ ${router} -eq 1 ];then
    if [[ '${listenport}' ]] && [[ ${listenport} -gt 0 ]]; then
      if [ ${drone} == 'default' ];then
        curl -X PUT -d "{\"id\": \"${project}\",\"name\": \"${project}\",\"address\": \"${host}\",\"port\": ${listen_port},\"tags\": [\"dev\"]}" http://consul-rg1.nwjx.com.cn/${env}/v1/agent/service/register
        curl -X PUT -d "{\"id\": \"${project}\",\"name\": \"${project}\",\"address\": \"${host}\",\"port\": ${listen_port},\"tags\": [\"dev\"]}" http://consul-rg2.nwjx.com.cn/${env}/v1/agent/service/register

        ssh -o StrictHostKeyChecking=no root@${host} "
          echo '${host} ${listen_port}' > /opt/linkerd/disco/${project_name}
        "
      else
        curl -X PUT -d "{\"id\": \"${project}-${drone}\",\"name\": \"${project}-${drone}\",\"address\": \"${drone_host}\",\"port\": ${listen_port},\"tags\": [\"dev\"]}" http://consul-rg1.nwjx.com.cn/${env}/v1/agent/service/register
        curl -X PUT -d "{\"id\": \"${project}-${drone}\",\"name\": \"${project}-${drone}\",\"address\": \"${drone_host}\",\"port\": ${listen_port},\"tags\": [\"dev\"]}" http://consul-rg2.nwjx.com.cn/${env}/v1/agent/service/register

        ssh -o StrictHostKeyChecking=no root@${host} "
          echo '${drone_host} ${listen_port}' > /opt/linkerd/disco/${project_name}-${drone}
          echo '${drone_host} ${listen_port}' > /opt/linkerd/disco/${project_name}-${drone_host}
        "
      fi
    fi
  fi
}

# ==============================kill service============================= #
function kill_service() {
  ssh -o StrictHostKeyChecking=no root@${host} "
    pidfile=${REMOTE_DIR}/${project}/spring-boot.pid
    [ -s \${pidfile} -a [ \`cat \${pidfile} | xargs ps | sed -n '2P' | wc -l\` -gt 0 ] ] && kill -9 \`cat \${pidfile}\`
    sleep 3
    # remove old package
    # [ -d ${REMOTE_DIR}/${project} -a ${REMOTE_DIR}/${project} != '/opt/vipkid/' ] && rm -rf ${REMOTE_DIR}/${project}
    [ -d ${REMOTE_DIR}/${project} ] || mkdir -p ${REMOTE_DIR}/${project}
  "
}

function scp_package() {
  remote_dir=${REMOTE_DIR}/${project}
  if [ -f ${package_jar} ];then
    if [ ${drone} == 'default' ];then
      scp -o StrictHostKeyChecking=no ${package_jar} root@${host}:${remote_dir}/${project}.jar
      [ -f ${package_source_jar} ] && scp -o StrictHostKeyChecking=no ${package_source_jar} root@${host}:${remote_dir}/${project}-sources.jar
    else
      scp -o StrictHostKeyChecking=no ${package_jar} root@${drone_host}:${remote_dir}/${project}.jar
      [ -f ${package_source_jar} ] && scp -o StrictHostKeyChecking=no ${package_source_jar} root@${host}:${remote_dir}/${project}-sources.jar
    fi
  fi
}

function start_service() {
  ((jacoco_port=listenport+20000))
  ssh -o StrictHostKeyChecking=no root@${host} "
  [ -d ${REMOTE_DIR}/${project} ] || exit 1
  [ -f ${REMOTE_DIR}/${project}/application.conf ] || exit 1
  [ -f ${REMOTE_DIR}/${project}/env.conf ] || exit 1

  cd ${REMOTE_DIR}/${project}
  [ -d /data/${project}/logs ] || mkdir -p /data/${project}/logs
  [ -d ${REMOTE_DIR}/${project}/logs ] || ln -s /data/${project}/logs ${REMOTE_DIR}/${project}/logs

  # vkcat
  VKCAT_AGENT_JAR=/root/vkcat/vkcat-agent/vkcat-agent.jar
  [ -f \${VKCAT_AGENT_JAR} -a ${vkcat_agent_set} == 'true' ] &&  VKCAT_AGENT_OPTS=\"-javaagent:\${VKCAT_AGENT_JAR} -DapplicationDomain=${project} -DvkcatDomain=vkcat.nwjx.com.cn:80\"
  # jacoco
  JACOCO_AGENT_JAR=/root/.ci_coverage/jacocoagent.jar
  if [ ${drone} == 'default' ];then
    [ -f \${JACOCO_AGENT_JAR} ] && JACOCO_OPTS=-javaagent:\${JACOCO_AGENT_JAR}=includes=com.vipkid.*,output=tcpserver,port=${jacoco_port},address=${host}
  else
    [ -f \${JACOCO_AGENT_JAR} ] && JACOCO_OPTS=-javaagent:\${JACOCO_AGENT_JAR}=includes=com.vipkid.*,output=tcpserver,port=${jacoco_port},address=${drone_host}
  fi
  # request header
  REQUEST_HEADER_JAR=/root/.vk_agent/agentutils-191031.jar
  REQUEST_DEP_JAR=/root/.vk_agent/requestHeaderAgent-dep-20190920.jar
  REQUEST_TS_LC=/root/.vk_agent/transmittable-thread-local-2.8.1.jar
  [ -f \${REQUEST_HEADER_JAR} -a -f \${REQUEST_DEP_JAR} -a -f \${REQUEST_TS_LC} ] && REQUEST_HEADER_OPTS=\"-javaagent:\${REQUEST_DEP_JAR} -javaagent:\${REQUEST_TS_LC} -Dloader.path=\${REQUEST_HEADER_JAR} -Dvk-l5d.redis.host=10.32.68.80:6379 -Dvk-l5d.vschedule.header=x-vk-mesh-router-key -Dvk-l5d.host.prefix=vk-l5d-\"

  sed -i \"s/{{VKCAT_AGENT_OPTS}}/\${VKCAT_AGENT_OPTS}/g\" application.conf
  sed -i \"s/{{JACOCO_OPTS}}/\${JACOCO_OPTS}/g\" application.conf
  sed -i \"s/{{REQUEST_HEADER_OPTS}}/\${REQUEST_HEADER_OPTS}/g\" application.conf

  if [ -f application.jar ];then
    chmod +x application.jar
    ./application.jar start
  else
    echo 'not found application.jar'
    exit 1
  fi
"
}

# ==============================write config============================== #
function write_config() {
  local_config=${TMP_DIR}/{env}-env.properties
  local_application=${TMP_DIR}/{env}-application.conf
  cp -f ${BASE_DIR}/deploy/env.properties ${local_config}
  cp -f ${BASE_DIR}/deploy/application.conf ${local_application}
  # env.properties
  sed -i "s/{{env}}/${env}/g" ${local_config}
  sed -i "s/{{host}}/${host}/g" ${local_config}
  sed -i "s/{{drone_host}}/${drone_host}/g" ${local_config}
  sed -i "s/{{business}}/${business}/g" ${local_config}
  sed -i "s/{{projectname}}/${project}/g" ${local_config}
  sed -i "s/{{listen_port}}/${listen_port}/g" ${local_config}
  sed -i "s/{{db_host}}/${db_host}/g" ${local_config}
  sed -i "s/{{db_port}}/${db_port}/g" ${local_config}


  #echo "gitpath=${gitpath}" >> ${local_config}
  #echo "branch=${branch}" >> ${local_config}

  # application.conf
  sed -i "s/{{listen_port}}/${listen_port}/g" ${local_application}
  sed -i "s/{{config_version}}/${config_version}/g" ${local_application}
  sed -i "s/{{config_safe_mode}}/${config_safe_mode}/g" ${local_application}
  sed -i "s/{{xmx}}/${xmx}/g" ${local_application}
  sed -i "s/{{debug_bool}}/${debug_bool}/g" ${local_application}

  if [ ${drone} == 'default' ];then
    temp_host=${host}
  else
    temp_host=${drone_host}
  fi
  scp -o StrictHostKeyChecking=no ${local_config} root@${temp_host}:${REMOTE_DIR}/${project}/env.properties
  scp -o StrictHostKeyChecking=no ${local_application} root@${temp_host}:${REMOTE_DIR}/${project}/application.conf
}

# ==============================health check============================== #
function live_detection() {
  for ((i=0;i<36;i++))
  do
    sleep 10
    if  [ ${drone} == 'default' ];then
      nc -v -w 1 ${host} ${listen_port}
    else
      nc -v -w 1 ${drone_host} ${listen_port}
    fi
    if [ $? -eq 0 ];then
      # 智能路由环境恢复流量
      register_consul
      exit 0
    fi
  done
}